'use strict';
module.exports = {
	/**
	 * 更新数据
	 * @url client/accounting/record/kh/updateKeepingData 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _, $ } = util;
		let { uid, keepingData, oldData} = data;
		let res = { code: 0, msg: "修改成功" };
		// 业务逻辑开始-----------------------------------------------------------
		if(keepingData == null || oldData == null ){
			return { code : 1001, msg : '参数错误' };
		}
		
		let {_id,isExpenses,icon,date,amount,remarks,books,revision} = keepingData;
		if(pubFun.isEmpty(icon) || pubFun.isEmpty(date) || pubFun.isEmpty(amount) || pubFun.isEmpty(books)){
			return { code : 1001, msg : '参数错误' };
		}
		
		const _amount = Math.trunc(amount * 100)
		const paramUtil = vk.require("service/client/accountbook/util/paramUtil");
		let paramData = await paramUtil.dealUpdateParam({isExpenses,icon:icon.icon,iconName:icon.name,date:pubFun.formatTimestamp(date),amount:_amount,remarks,"revision": revision ? revision : 0 });
		
		// 开启事务
		const transaction = await vk.baseDao.startTransaction();
		try {
			// 更新数据
			let row = await vk.baseDao.update({
				db: transaction, // 本次数据库语句带上事务对象（重要，必须带上）
				dbName:"db-book-keeping-data",
				whereJson: {
					_id: _.eq(_id)
				},
				dataJson: paramData
			 });
			
			if(row <= 0 ) {
				throw new Error("更新失败");
			}
			
			let accountBook = books[0]
			let _dataJson = {"revision": accountBook.revision + 1}
			if(keepingData.isExpenses === "true") {
				_dataJson.totalEcpenditure = accountBook.totalEcpenditure - oldData.amount + _amount
				_dataJson.surplus = accountBook.surplus - oldData.amount + _amount
			}
			else {
				_dataJson.totalRevenue = accountBook.totalRevenue - oldData.amount + _amount
				_dataJson.surplus = accountBook.surplus - oldData.amount + _amount
			}
			
			// 更新账本
			let row2 = await vk.daoCenter.accountBookDao.updateById({
			 	id: accountBook._id, 
			 	dataJson: _dataJson
			 });
			
			if(row2 <= 0 ) {
				throw new Error("更新失败" + accountBook._id);
			}
			
			// 提交事务
			await transaction.commit();
		} catch (err) {
			// 事务回滚
			await vk.baseDao.rollbackTransaction({db: transaction,err});
			console.error(`transaction error`, err)
		    return {
		      code: -1,
		      msg: "数据库写入异常,事务已回滚",
		      err: {
		        message: err.message,
		        stack: err.stack
		      },
			}
		}
		
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}